<template>
  <div>
    <vue-cropper
        ref="cropper"
        :img="imageUrl"
        :info="true"
        :autoCrop="options.autoCrop"
        :autoCropWidth="options.autoCropWidth"
        :autoCropHeight="options.autoCropHeight"
        :fixedBox="options.fixedBox"
        :outputType="options.outputType"
        @realTime="realTime"
        style="width: 100%; height: 400px"
    />
    <a-button type="primary" @click="determine">裁剪</a-button>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import 'vue-cropper/dist/index.css'
import { VueCropper }  from "vue-cropper";

const { proxy } = getCurrentInstance()
const props = defineProps({
  imageUrl: String,
  aspectRatio: {
    type: Number,
    default: 1
  }
});
const previews = ref({
  url: ''
})
const options = reactive({
  autoCropWidth: 200, // 默认生成截图框宽度 默认容器的 80%
  autoCropHeight: 200, // 默认生成截图框高度 默认容器的 80%
  outputType: 'png', // 裁剪生成图片的格式 jpeg, png, webp
  autoCrop: true, // 是否默认生成截图框
  fixedBox: false // 固定截图框大小
})

const emit = defineEmits(['cropped']);

const cropper = ref(null);
// 修改图片大小 正数为变大 负数变小
const changeScale = (num) => {
  num = num || 1
  proxy.$refs.cropper.changeScale(num)
}
// 向左边旋转90度
const rotateLeft = () => {
  proxy.$refs.cropper.rotateLeft()
}
// 向右边旋转90度
const rotateRight = () => {
  proxy.$refs.cropper.rotateRight()
}
// 实时预览事件
const realTime = (data) => {
  previews.value = data
}


// 关闭弹窗
const beforeClose = () => {
}
// 提交图片
const determine = () => {
  /*options.img = null
  previews.value.url = ''
  console.log('previews.value', previews.value)
  emit('confirm')*/
  cropper.value.getCropBlob(async (data) => {
    console.log('data', data)
    const res = new File([data], props.imageUrl, {
      type: data.type,
      lastModified: Date.now(),
    })
    console.log('res', res)
    emit('cropped', res);

    /*const imgUrl = window.URL.createObjectURL(data);

    const response = await fetch(imgUrl);
    const blobData = await response.blob();

    const formData = new FormData();
    formData.append('file', blobData, 'filename.png');
    imageUpload(formData).then(res => {
      isLoading.value = false
      show.value = false
      props.getPropsUrl(res.data.data.url)
    });*/
  })
}

/*const cropImage = () => {
  const canvas = cropper.value.getCroppedCanvas();
  emit('cropped', canvas.toDataURL());
};*/
</script>